package com.zqq.progrsssview;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;

/**
 * @author zqq on 2018-11-21
 */
public class LoadingDialog extends Dialog {

    private Context context;
    private View view;
    Activity activity;
    //用来控制是否按返回键取消网络请求（因为HomeFragment进来就显示了加载框，并且没有接口调用加载框，
    // 所以可以这么使用，如果存在多个加载框同时加载的情况，此方法不行）
    private int flag;


    public LoadingDialog(@NonNull Context context) {
        super(context, R.style.Dialog_Fullscreen);
        this.context = context;
        activity = (Activity) context;
    }

    public LoadingDialog(@NonNull Context context, int flag) {
        super(context, R.style.Dialog_Fullscreen);
        this.context = context;
        activity = (Activity) context;
        this.flag = flag;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (view == null) {
            view = LayoutInflater.from(context).inflate(R.layout.dialog_loading, null);
            setContentView(view);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (view != null) {
            view = null;
        }
    }

    @Override
    public void dismiss() {
        if (activity != null && !activity.isFinishing()) {
            super.dismiss();
        }
    }

    @Override
    public void setOnDismissListener(@Nullable DialogInterface.OnDismissListener listener) {
        super.setOnDismissListener(listener);
    }

    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (flag == 1) {
////                RxBus.getInstance().post(new Event(CANCEL_NETWORK));
//            }
//            return true;
//        }
        return super.onKeyDown(keyCode, event);
    }
}
